package atguigu.day02;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyResource{
    public synchronized void xian(){
        System.out.println(Thread.currentThread().getName()+"--------m1");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



    Lock lock = new ReentrantLock();
    public void m2() throws InterruptedException {
        if (lock.tryLock(4,TimeUnit.SECONDS)){
            System.out.println(Thread.currentThread().getName()+"--------m1");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }else {
            System.out.println(Thread.currentThread().getName()+"抢线成功");
        }
    }



}


public class SynAndLock {

    public static void main(String[] args) {
        MyResource resource = new MyResource();
        new Thread(() -> {
            try {
                resource.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"线程1").start();


        new Thread(() -> {
            try {
                resource.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"线程2").start();


    }
}
